package com.qingjiang.projectschedule.utils;

import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;

@Component
public class HttpRequest {
    public static void main(String[] args) {
        String url = "http://datainterface.qdc.com.cn/api/WebServices/EMPService.asmx";
        String param = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\\r\\n<soap12:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap12=\"http://www.w3.org/2003/05/soap-envelope\">\\r\\n  <soap12:Header>\\r\\n    <SecurityToken xmlns=\"http://datainterface.qdc.com.cn/\">\\r\\n      <UserName>iAMSUSER</UserName>\\r\\n      <Key>B12BD8A9D67B4B8CAFECD121E67169AE</Key>\\r\\n    </SecurityToken>\\r\\n  </soap12:Header>\\r\\n  <soap12:Body>\\r\\n    <StdEmpOrganizationListGet xmlns=\"http://datainterface.qdc.com.cn/\">\\r\\n      <iDeptId></iDeptId>\\r\\n    </StdEmpOrganizationListGet>\\r\\n  </soap12:Body>\\r\\n</soap12:Envelope>";
        String s = sendPost(url, param);
        System.out.println(s);
    }

    public static String sendPost(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        StringBuilder result = new StringBuilder();
        try {
            URL realUrl = new URL(url);
            URLConnection connection = realUrl.openConnection();
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "keep-alive");
            connection.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36");
//            connection.setRequestProperty("SOAPAction", "http://datainterface.qdc.com.cn/StdEmpOrganizationListGet");
            connection.setRequestProperty("Content-Type", "application/soap+xml; charset=utf-8");
            connection.setDoOutput(true);
            connection.setDoInput(true);
            out = new PrintWriter(connection.getOutputStream());
            out.print(param);
            out.flush();
            in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return result.toString();
    }
}
